package breeze.library.orchid.service;

import android.annotation.SuppressLint;
import android.content.Context;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import breeze.library.orchid.utils.OrchidFileUtils;


public class OrchidExceptionCatcher implements Thread.UncaughtExceptionHandler {

    @SuppressLint("StaticFieldLeak")
    private static OrchidExceptionCatcher mOrchidExceptionCatcher;

    @SuppressLint("StaticFieldLeak")
    public static Context mContext;

    public static OrchidExceptionCatcher getInstance(Context context) {
        if (mOrchidExceptionCatcher == null) {
            mOrchidExceptionCatcher = new OrchidExceptionCatcher(context);
        }
        return mOrchidExceptionCatcher;
    }

    public OrchidExceptionCatcher(Context context) {
        mContext = context;
    }

    @Override
    public void uncaughtException(Thread p1, Throwable p2) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        p2.printStackTrace(printWriter);
        Throwable throwable = p2.getCause();
        while (throwable != null) {
            throwable.printStackTrace(printWriter);
            throwable = throwable.getCause();
        }
        String Exception_content = writer.toString();
        try {
            String path = OrchidFileUtils.getExternalCacheFile(mContext, "Exception") + "ErrorLog.txt";
            OrchidFileUtils.createMultiFilePath(path);
            OrchidFileUtils.writeFileContent(path, Exception_content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
